package com.lagou.dubbo.filter;

import com.lagou.dubbo.common.CommonUtils;
import com.lagou.dubbo.common.Constants;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Activate(group = {CommonConstants.CONSUMER}, value = "TransportIPFilter")
public class TransportIPFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        // 保存请求ip信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        RpcContext.getContext().setAttachment(Constants.REQUEST_IP, CommonUtils.getRequestIp(request));

        return invoker.invoke(invocation);
    }
}
